#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/9/21 0021 19:11
# @Author  : GXl
# @File    : models.py
# @Software: win10 Tensorflow1.13.1 python3.7

from config import Config
from  utils import logutils
from . import db
from sqlalchemy.orm import class_mapper
#token验证使用
import time
import jwt
from passlib.apps import custom_app_context as pwd_context
from werkzeug.security import generate_password_hash, check_password_hash

############################
#注意：
#1、每次migrate之前，要先在terminal里面设置FLASK_APP 环境变量
#2、然后运行 $ flask db migrate   和  $ flask db upgrade 更新数据库
######################

logger=logutils.getlogger(__file__)
config=Config()

class DictModel:
    def as_dict(obj):
        return dict((col.name, getattr(obj, col.name)) \
                    for col in class_mapper(obj.__class__).mapped_table.c)



#多继承，增加as_dict
class User(db.Model,DictModel):
    __tablename__  = 'user'
    id = db.Column(db.INTEGER,primary_key=True,autoincrement=1000)
    name = db.Column(db.String(255), unique=True, index=True)
    username = db.Column(db.String(100))
    password = db.Column(db.String(255))
    avatar = db.Column(db.String(255),default="https://gw.alipayobjects.com/zos/rmsportal/jZUIxmJycoymBprLOUbT.png")
    status = db.Column(db.SMALLINT)
    telephone = db.Column(db.String(20))
    lastLoginIp = db.Column(db.String(15))
    lastLoginTime = db.Column(db.BIGINT)
    creatorId = db.Column(db.String(20))
    createTime = db.Column(db.BIGINT)
    deleted = db.Column(db.SMALLINT)
    roleId = db.Column(db.String(20))
    lang = db.Column(db.String(10),default="zh-CN")
    token = db.Column(db.String(255))

    def to_dict(self):
        return {
            'id':self.id,
            'name':self.name,
            'username':self.username,
            'password':self.password,
            'avatar':self.avatar,
            'status':self.status,
            'telephone':self.telephone,
            'lastLoginIp':self.lastLoginIp,
            'lastLonginTime':self.lastLonginTime,
            'creatorId':self.creatorId,
            'createTime':self.createTime,
            'delete':self.delete,
            'roleId':self.roleId,
            'lang':self.lang,
            'token':self.token
        }
    #
    # def as_dict(obj):
    #     return dict((col.name, getattr(obj, col.name)) \
    #                 for col in class_mapper(obj.__class__).mapped_table.c)

    # 检查密码是否正确
    # # 生成密码散列方法
    # def hash_password(self):
    #     self.password_hash = pwd_context.encrypt(self.password)

    # 校验密码方法
    def verify_password(self, password):
        return pwd_context.verify(password, self.password_hash)

    # 生成token方法
    def generate_auth_token(self):
        print("self id ", self.id)
        #刷新token
        self.token=jwt.encode({'id': self.id, 'username': self.username, 'role': self.roleId,'exp': time.time() + 600},config.SECRET_KEY,algorithm='HS256')
        return self.token

    def updateLastloginTime(self):
        db.session.execute("""update user set lastLoginTime={} where id={}""".format(int(time.time()), self.id))
        db.session.commit()
    # 校验token方法
    @staticmethod
    def verify_auth_token(token):
        try:
            data = jwt.decode(token, config.SECRET_KEY,algorithms=['HS256'])
        except Exception as e:
            print(e)
            return False
        #如果用户token过期
        if time.time()>data['exp']:
            logger.info('用户id {} token过期'.format(data['id']))
            return False
        user = User.query.filter(User.id == data['id']).first()
        #如果找不到用户
        if not user:
            return False
        # user.updateLastloginTime()
        logger.debug('验证token成功，获取到用户id {}，用户名{}'.format(user.id,user.username))
        return user

    def __repr__(self):
        return  '\r\n'.join(['{}={}'.format(key,val) for key,val in self.__dict__.items()])

#用户收藏表
class UserCollection(db.Model,DictModel):
    __tablename__  = 'usercollection'
    id = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
    userid=db.Column(db.INTEGER,index=True)
    username = db.Column(db.String(255),index=True)
    bookid=db.Column(db.INTEGER)
    douban_id = db.Column(db.INTEGER)

    def __repr__(self):
        return  '\r\n'.join(['{}={}'.format(key,val) for key,val in self.__dict__.items()])

#购物车表
class ShoppingCart(db.Model,DictModel):
    __tablename__  = 'shoppingcart'
    id = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
    userid=db.Column(db.INTEGER,index=True)
    username = db.Column(db.String(255),index=True)
    bookid=db.Column(db.INTEGER)
    douban_id = db.Column(db.INTEGER)
    bookname=db.Column(db.String(100))
    authors=db.Column(db.String(100))
    price = db.Column(db.String(20))
    num=db.Column(db.INTEGER)
    status=db.Column(db.SMALLINT,default=1,comment="购物车状态，为0表示已经生成对应订单，为1表示有效，为-1表示已删除")
    createTime = db.Column(db.BIGINT)


    def __repr__(self):
        return  '\r\n'.join(['{}={}'.format(key,val) for key,val in self.__dict__.items()])
    def __str__(self):
        return self.__repr__()

#用户订单表
class UserOrder(db.Model):
    __tablename__  = 'userorder'
    id = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
    orderid= db.Column(db.String(50))
    userid=db.Column(db.INTEGER,index=True)
    content=db.Column(db.Text,comment="这里偷懒了，用json文本的形式，存储整个订单信息")
    createtime = db.Column(db.BIGINT)


    def __repr__(self):
        return  '\r\n'.join(['{}={}'.format(key,val) for key,val in self.__dict__.items()])
    def __str__(self):
        return self.__repr__()

class Address(db.Model,DictModel):
    __tablename__ = 'address'
    id = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
    userid = db.Column(db.INTEGER, index=True)
    name = db.Column(db.String(255), index=True,comment="收货人姓名")
    telephone = db.Column(db.String(20),comment="收货人手机号")
    isdefault=db.Column(db.SMALLINT,default=1,comment="状态，为1表示是默认收货地址，为0表示有效，为-1表示已删除")
    address = db.Column(db.String(255),comment="收货地址")
    createTime = db.Column(db.BIGINT,comment="时间戳，默认UTC秒数")

    def __repr__(self):
        return  '\r\n'.join(['{}={}'.format(key,val) for key,val in self.__dict__.items()])
    def __str__(self):
        return self.__repr__()

#书籍详情
class BookDetail(db.Model,DictModel):
    __tablename__  = 'bookdetail'
    id = db.Column(db.INTEGER,primary_key=True,autoincrement=True)
    slug=db.Column(db.String(64), unique=True)
    name = db.Column(db.String(100),index=True)
    sub_name = db.Column(db.String(255))
    alt_name = db.Column(db.String(255))
    img = db.Column(db.String(100))
    cover = db.Column(db.String(255))
    summary = db.Column(db.TEXT)
    authors = db.Column(db.String(255))
    author_intro = db.Column(db.TEXT)
    translators = db.Column(db.String(255))
    series = db.Column(db.String(255))
    publisher = db.Column(db.String(255))
    publish_date = db.Column(db.String(255))
    pages = db.Column(db.String(255))
    price = db.Column(db.String(20))
    binding = db.Column(db.String(255))
    isbn = db.Column(db.String(50))
    tags = db.Column(db.String(255))
    douban_id = db.Column(db.INTEGER,unique=True, index=True)
    douban_score = db.Column(db.INTEGER)
    douban_votes = db.Column(db.INTEGER)
    created_at = db.Column(db.TIMESTAMP)
    updated_at = db.Column(db.TIMESTAMP)

    def __repr__(self):
        return  '\r\n'.join(['{}={}'.format(key,val) for key,val in self.__dict__.items()])
